package yxy.game.pm2.bean.module;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RBucket;
import org.redisson.api.RLock;

import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;

public abstract class BaseGameRedisBean {
	// redis==========================================================================

	static protected RedisConnection redis() {
		return RedisManager.getInstance().getConnection(RedisType.REDIS_GAME);
	}

	static protected <V> RBucket<V> touchBucket(String key) throws RedisException {
		return RedisManager.client(redis()).getBucket(key);
	}

	protected static <V extends BaseGameRedisBean> V getv(String key) throws RedisException {
		RBucket<V> bucket = touchBucket(key);
		return bucket.get();
	}

	protected static <V extends BaseGameRedisBean> void setv(String key, V m) throws RedisException {
		RBucket<V> bucket = touchBucket(key);
		bucket.set(m);
	}

	//带过期时间
    protected static <V extends BaseGameRedisBean> void setv(String key, V m, long expire, TimeUnit timeUnit) throws RedisException {
        RBucket<V> bucket = touchBucket(key);
        bucket.set(m, expire, timeUnit);
    }

	// lock==========================================================================

	abstract public String lockKey();

	protected RLock lock;

	protected RLock rLock() {
		if (lock == null) {
			lock = redis().client().getLock(lockKey());
		}
		return lock;
	}

	public boolean tryLock() throws InterruptedException {
//		System.err.println("tryLock::::	" + lockKey() + "	::" + lock());
		return rLock().tryLock(20, 10, TimeUnit.SECONDS);
	}

	public void unlock() {
//		System.err.println("unlock::::	" + lockKey() + "	::" + lock());
		rLock().unlock();
		lock = null;
	}

	// locknew==========================================================================

	public static RedisLock getLock(String lockKey) {
//		return redis().client().getLock(lockKey);
		return new RedisLock(redis().client().getLock(lockKey));

	}

	static public RLock getRedisLock(String lockKey)  {
		return redis().client().getLock(lockKey);
	}



//	public static boolean tryLock(RLock lock) throws InterruptedException {
//		if (lock == null) {
//			return true;
//		}
//		return lock.tryLock(20, 10, TimeUnit.SECONDS);
//	}


//	public static
}
